import { useState } from "react";

export default function Task({ todo, onChangeTodo, onDeleteTodo }) {
  const [isEditing, setIsEditing] = useState(false);
  let textContent;

  if (isEditing) {
    textContent = (
      <>
        <input type="text" value={todo.title} onChange={(e) => {
          onChangeTodo({
            ...todo,
            title: e.target.value
          })
        }} />
        <button style={{ marginLeft: '15px' }} onClick={() => setIsEditing(false)}>保存</button>
      </>
    )
  } else {
    textContent = (
      <>
        <span>{todo.title}</span>
        <button style={{ marginLeft: '15px' }} onClick={() => setIsEditing(true)}>编辑</button>
      </>
    )
  }

  return (
    <>
      <input type="checkbox" checked={todo.done} onChange={e => {
        onChangeTodo({
          ...todo,
          done: e.target.checked
        })
      }} />
      {textContent}
      <button style={{ marginLeft: '15px' }} onClick={() => onDeleteTodo(todo.id)}>删除</button>
    </>
  )
}